/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 指定登记&发行网站： https://www.zhiqim.com/ 欢迎加盟知启蒙，[编程有你，知启蒙一路随行]。
 *
 * 本文采用《知启蒙许可证》，除非符合许可证，否则不可使用该文件！
 * 1、您可以免费使用、修改、合并、出版发行和分发，再授权软件、软件副本及衍生软件；
 * 2、您用于商业用途时，必须在原作者指定的登记网站，按原作者要求进行登记；
 * 3、您在使用、修改、合并、出版发行和分发时，必须包含版权声明、许可声明，及保留原作者的著作权、商标和专利等知识产权；
 * 4、您在互联网、移动互联网等大众网络下发行和分发再授权软件、软件副本及衍生软件时，必须在原作者指定的发行网站进行发行和分发；
 * 5、您可以在以下链接获取一个完整的许可证副本。
 * 
 * 许可证链接：http://zhiqim.org/licenses/zhiqim_register_publish_license.htm
 * 
 * 除非法律需要或书面同意，软件由原始码方式提供，无任何明示或暗示的保证和条件。详见完整许可证的权限和限制。
 */
package org.zhiqim.lottery.action;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Context;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.context.service.UploadService;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.onex.IsNumeric;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Files;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.lottery.dbo.LotteryInfo;
import org.zhiqim.lottery.dbo.LotteryUser;
import org.zhiqim.manager.ZmrConstants;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 抽奖用户
 *
 * @version v1.4.1 @author zouzhigang 2021-4-17 新建与整理
 */
public class UserAction extends StdSwitchAction implements ZmrConstants
{
    protected void validateId(HttpRequest request)
    {
        request.addValidate(new IsNumeric("userId","抽奖用户编号不能为空"));
    }
    
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsNumeric("lotteryId", "抽奖编号不能为空"));
        request.addValidate(new IsNumeric("userType", "抽奖用户类型不能为空"));
        request.addValidate(new IsNotEmpty("userName", "抽奖用户名称不能为空"));
        request.addValidate(new IsNumeric("userLuck", "抽奖是否已中奖不能为空"));
    }

    protected void list(HttpRequest request) throws Exception
    {
        long lotteryId = request.getParameterLong("lotteryId");
        if (lotteryId == -1)
        {
            request.returnHistory("请选择一个有效的抽奖信息");
            return;
        }
        
        LotteryInfo lottery = ORM.table().item(LotteryInfo.class, lotteryId);
        if (lottery == null)
        {
            request.returnHistory("请选择一个有效的抽奖信息");
            return;
        }
        
        int page = request.getParameterInt("page");
        int pageSize = request.getContextAttributeInt(ZMR_PAGE_SIZE, 20);
        int userLuck = request.getParameterInt("userLuck");
        
        Selector selector = new Selector();
        selector.addMust("lotteryId", lotteryId);
        selector.addMaybeLike("userName", request.getParameter("userName"));
        selector.addMaybe("userType", request.getParameterInt("userStatus"));
        if (userLuck == 0)
            selector.addMaybe("userLuck", 0);
        else if (userLuck == 1)
            selector.addMaybeThenG("userLuck", 0);
        selector.addOrderbyDesc("userLuck");
        
        PageResult<LotteryUser> result = ORM.table().page(LotteryUser.class, page, pageSize, selector);
        result.addConditionMap(request.getParameterMap());
        
        request.setAttribute("lotteryId", lotteryId);
        request.setAttribute("lottery", lottery);
        request.setAttribute("result", result);
    }

    protected void insert(HttpRequest request) throws Exception
    {
        LotteryUser user = request.getParameter(LotteryUser.class);
        user.setUserId(Ids.longId13());
        ORM.table().insert(user);
        
        //返回参数
        request.addParam("lotteryId", user.getLotteryId());
    }

    protected void modify(HttpRequest request) throws Exception
    {
        long userId = request.getParameterLong("userId");
        LotteryUser item = ORM.table().item(LotteryUser.class, userId);
        if(item == null)
        {
            request.returnHistory("该抽奖用户不存在，请重新选择");
            return;
        }
        
        LotteryInfo lottery = ORM.table().item(LotteryInfo.class, item.getLotteryId());
        if (lottery == null)
        {
            request.returnHistory("请选择一个有效的抽奖信息");
            return;
        }
        
        request.setAttribute("lottery", lottery);
        request.setAttribute("item", item);
    }
    
    protected void update(HttpRequest request) throws Exception
    {
        LotteryUser user = request.getParameter(LotteryUser.class);
        
        Updater updater = new Updater();
        updater.addMust("userId", user.getUserId());
        updater.addField("userName", user.getUserName());
        updater.addField("userType", user.getUserType());
        updater.addField("userLuck", user.getUserLuck());
        
        ORM.table().update(LotteryUser.class, updater);
        
        //返回参数
        request.addParam("lotteryId", user.getLotteryId());
    }

    protected void delete(HttpRequest request) throws Exception
    {
        long userId = request.getParameterLong("userId");
        LotteryUser item = ORM.table().item(LotteryUser.class, userId);
        if(item == null)
        {
            request.returnHistory("该抽奖信息不存在");
            return;
        }
        
        ORM.table().delete(LotteryUser.class, userId);
        
        //返回参数
        request.addParam("lotteryId", item.getLotteryId());
    }
    
    /** 清空所有用户 */
    public void clear(HttpRequest request) throws Exception
    {
        long lotteryId = request.getParameterLong("lotteryId");
        if(lotteryId == -1 || ORM.table().count(LotteryInfo.class, lotteryId) == 0)
        {
            request.setResponseError("该抽奖信息不存在");
            return;
        }
        
        ORM.table().delete(LotteryUser.class, new Selector("lotteryId", lotteryId));
    }
    
    /** 重建200个演示用户 */
    public void reset(HttpRequest request) throws Exception
    {
        long lotteryId = request.getParameterLong("lotteryId");
        if(lotteryId == -1 || ORM.table().count(LotteryInfo.class, lotteryId) == 0)
        {
            request.setResponseError("该抽奖信息不存在");
            return;
        }
        
        for (int i=0;i<200;i++)
        {
            LotteryUser user = new LotteryUser();
            user.setLotteryId(lotteryId);
            user.setUserId(Ids.longId13());
            user.setUserName("演示用户"+(i+1));
            user.setUserLuck(0);
            user.setUserType(1);
            
            ORM.table().replace(user);
        }
    }
    
    /** 上传用户 */
    public void upload(HttpRequest request) throws Exception
    {
        long lotteryId = request.getParameterLong("lotteryId");
        if(lotteryId == -1 || ORM.table().count(LotteryInfo.class, lotteryId) == 0)
        {
            request.setResponseError("该抽奖信息不存在");
            return;
        }
        
        String fileUrl = request.getParameter("fileUrl");
        String fileName = Files.getFileName(fileUrl);
        if (!Strings.endsWith(fileName, ".txt"))
        {
            request.setResponseError("仅支持上传的TXT文件格式，一行一个用户姓名");
            return;
        }
        
        UploadService service = ((Context)request.getContext()).getServiceExecutor().getUploadService();
        String uploadRootPath = service.getUploadRootDir();
        String filePath = uploadRootPath + fileName;
        String content = Files.readUTF8(filePath);
        
        String[] lines = content.split("\n");
        for (String line : lines)
        {
            line = Strings.trim(line);
            if (Validates.isEmptyBlank(line))
                continue;
            
            if (line.length() > 30)
            {
                request.setResponseError("名称太长，不支持");
                return;
            }
            
            LotteryUser user = new LotteryUser();
            user.setLotteryId(lotteryId);
            user.setUserId(Ids.longId13());
            user.setUserName(line);
            user.setUserLuck(0);
            user.setUserType(1);
            
            ORM.table().replace(user);
        }
    }
}